# -*-coding: utf-8 -*-
import csv, codecs, logging
from django.core.management.base import BaseCommand
from ftbexplorer.fnd.models import Connecteur 
from optparse import make_option

class CommentedFile:
    def __init__(self, f, commentstring="#"):
        self.f = f
        self.commentstring = commentstring

    def next(self):
        line = self.f.next()
        while line.startswith(self.commentstring):
            line = self.f.next()
        return line

    def __iter__(self):
        return self

class ConnecteurTSVReader(object):
    def __init__(self, file):
        self.csvreader = csv.reader(file, delimiter="\t")
        self.line_num = self.csvreader.line_num
        
    def __iter__(self):
        return self
    
    def next(self):
        n = self.csvreader.next()
        while n and n[0][0] == "#":
            n = self.csvreader.next()
        n = map(lambda x: x.decode("utf8"), n)
        n = map(lambda x: {u"?": None}.get(x, x), n)
        self.line_num = self.csvreader.line_num
        return n
        


class Translator(object):
    categorie = {
        "csu": "C",
        "prep": "P",
        "adv": "ADV",
        "cco": "ADV",
        }

    type_relation = {
        "coord": "C",
        "sub": "S",
        None: None,
        }

class Command(BaseCommand):
    help = "Lis la liste des connecteurs"
    
    option_list = BaseCommand.option_list + (
        make_option('--debug', action='store_true', dest='debug', default=False,
            help='Display debug informations'),
        make_option('--validate', action='store_true', dest='validate', default=False,
            help='Validate liste against database model.'),
        make_option('--reset', action='store_true', dest='reset', default=False,
            help='Clear database before importing.'),
    )
    
    def handle(self, *args, **options):
        # congifure logging
        LOGGING_FORMAT="%(asctime)s - %(levelname)s - %(message)s"
        if options.get("debug", False):
            logging.basicConfig(format=LOGGING_FORMAT, level=logging.DEBUG)
        else:
            logging.basicConfig(format=LOGGING_FORMAT, level=logging.INFO)

        self.validate_file(open(args[0], "r"))
        if not options.get("validate", False):
            if options.get("reset", False):
                self.reset()
            self.import_file(open(args[0], "r"))
            
            
            
    def validate_file(self, stream):
        reader = ConnecteurTSVReader(stream)
        for a_row in reader:
            try:
                assert len(a_row) == 5, "Taille invalide à la ligne %d" % reader.line_num
                connecteur, cat, typerel, rel, ex = a_row
                assert Translator.categorie.get(cat, False), "Catgorie %s invalide ligne %d (%s)" % (cat, reader.line_num, connecteur)
                if typerel:
                    assert Translator.type_relation.get(typerel, False), "Type de relation invalide : %s ligne %d (%s)" % (typerel, reader.line_num, connecteur)
            except AssertionError, e:
                logging.error(e)
        return True
        
    def import_file(self, stream):
        reader = ConnecteurTSVReader(stream)
        for a_row in reader:
            try:
                connecteur, cat, typerel, rel, ex = a_row
                obj = Connecteur(
                    connecteur=connecteur, 
                    cat=Translator.categorie[cat], 
                    type_relation= Translator.type_relation[typerel], 
                    relation=rel, exemple=ex)
                obj.save()
            except Exception, e:
                logging.error(str(e) + " [line %d]" % reader.line_num)
                
    def reset(self):
        things = Connecteur.objects.all()
        for t in things:
            del t
    
        
